package com.runen.infinitemovement.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.MyDynamicStateAdapterV2;
import com.runen.infinitemovement.adapter.MyHomeBannerAdapter;
import com.runen.infinitemovement.adapter.MyHomeMedalAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.ActivityAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.DynamicEntity;
import com.runen.infinitemovement.model.entity.MyOngoingActivityListsBean;
import com.runen.infinitemovement.model.entity.PersonEntity;
import com.runen.infinitemovement.model.enums.ActivityCompat;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.notchtool.NotchTools;
import com.runen.infinitemovement.tool.notchtool.core.NotchProperty;
import com.runen.infinitemovement.tool.notchtool.core.OnNotchCallBack;
import com.runen.infinitemovement.widget.CustomLoadMoreView;
import com.runen.infinitemovement.widget.IndicatorSeekBar;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.ToastUtils;
import com.youth.banner.Banner;
import com.youth.banner.indicator.RectangleIndicator;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.BlurTransformation;

import static com.runen.infinitemovement.tool.GlideOptions.bitmapTransform;

/**
 * Create by LiaoDuanHong
 * Create on
 */
public class MyHomeActivityV2 extends BaseActivity {
    @BindView(R.id.rci_user_header)
    RoundedCornersImage rci_user_header;
    @BindView(R.id.tv_user_name)
    TextView tv_user_name;
    @BindView(R.id.tv_tenant_name)
    TextView tv_tenant_name;
    @BindView(R.id.tv_describe)
    TextView tv_describe;
    @BindView(R.id.tv_sports_num)
    TextView tv_sports_num;
    @BindView(R.id.tv_distance_km)
    TextView tv_distance_km;
    @BindView(R.id.tv_like_num)
    TextView tv_like_num;
    @BindView(R.id.tv_medal_count)
    TextView tv_medal_count;
    @BindView(R.id.tv_level)
    TextView tv_level;
    @BindView(R.id.tv_score)
    TextView tv_score;
    @BindView(R.id.tv_pass)
    TextView tv_pass;
    @BindView(R.id.btn_finish)
    Button btnFinish;
    @BindView(R.id.tv_start_end_name)
    TextView tv_start_end_name;
    @BindView(R.id.tv_finish_load)
    TextView tv_finish_load;
    @BindView(R.id.indicator_seek_bar_we_long)
    IndicatorSeekBar indicator_seek_bar_we_long;
    @BindView(R.id.iv_bg)
    ImageView iv_bg;
    @BindView(R.id.ll_like)
    LinearLayout ll_like;
    @BindView(R.id.ll_focus)
    LinearLayout ll_focus;
    @BindView(R.id.tv_add_focus)
    TextView tv_add_focus;
    @BindView(R.id.tv_add_like)
    TextView tv_add_like;
    @BindView(R.id.iv_add_focus)
    ImageView iv_add_focus;
    @BindView(R.id.iv_add_like)
    ImageView iv_add_like;
    @BindView(R.id.rv_badge_list)
    RecyclerView rv_badge_list;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.iv_medal_name)
    ImageView iv_medal_name;
    @BindView(R.id.rv_my_status_list)
    RecyclerView rvMyStatusList;
    @BindView(R.id.ll_medal_null)
    LinearLayout ll_medal_null;
    @BindView(R.id.ll_activity_null)
    LinearLayout ll_activity_null;
    @BindView(R.id.ll_dynamic_null)
    LinearLayout ll_dynamic_null;
    @BindView(R.id.tv_tiaozhan)
    TextView tv_tiaozhan;

    private String userId;
    private PersonEntity.DataBean dataBean;
    private MyHomeMedalAdapter myHomeMedalAdapter;
    private MyDynamicStateAdapterV2 myDynamicStateAdapter;

    private int page = 1;
    private int size = 10;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_home_v2;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        NotchTools.getFullScreenTools().translucentStatusBar(this, new OnNotchCallBack() {
            @Override
            public void onNotchPropertyCallback(NotchProperty notchProperty) {
                RelativeLayout.LayoutParams lp1 = (RelativeLayout.LayoutParams) btnFinish.getLayoutParams();
                lp1.topMargin = btnFinish.getTop() + CommonUtil.getStatusBarHeight(MyHomeActivityV2.this);
                btnFinish.setLayoutParams(lp1);
                RelativeLayout.LayoutParams lp2 = (RelativeLayout.LayoutParams) iv_bg.getLayoutParams();
                lp2.height = CommonUtil.dp2px(MyHomeActivityV2.this, 158)
                        + CommonUtil.getStatusBarHeight(MyHomeActivityV2.this);
                iv_bg.setLayoutParams(lp2);
            }
        });
        userId = getIntent().getStringExtra(ActivityCompat.USER_ID);
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                initData();
                initDynamicList();
            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        rvMyStatusList.setLayoutManager(layoutManager);
        myDynamicStateAdapter = new MyDynamicStateAdapterV2(this, 1);
        myDynamicStateAdapter.getLoadMoreModule().setLoadMoreView(new CustomLoadMoreView());
        rvMyStatusList.setAdapter(myDynamicStateAdapter);
        myDynamicStateAdapter.getLoadMoreModule().setAutoLoadMore(false);
        myDynamicStateAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                page++;
                initDynamicList();
            }
        });
        initData();
        initDynamicList();
    }

    private void initData() {
        srl.setRefreshing(true);
        String params = "?userId=%s";
        new UserAPI().getPersonPagerInfo(String.format(params, userId), new BaseResultCallback<PersonEntity>() {
            @Override
            public void onResponse(PersonEntity response) {
                srl.setRefreshing(false);
                if (response != null && response.code == 0) {
                    dataBean = response.data;
                    setView(response.data);
                }
            }
        });
    }

    private void initDynamicList() {
        String params = "?toUserId=%s&page=%s&limit=%s";
        new UserAPI().getUserDynamicList(String.format(params, userId, page, size), new BaseResultCallback<DynamicEntity>() {
            @Override
            public void onResponse(DynamicEntity response) {
                if (response != null && response.code == 0 && response.data != null && response.data.size() > 0) {
                    rvMyStatusList.setVisibility(View.VISIBLE);
                    ll_dynamic_null.setVisibility(View.GONE);
                    if (page == 1) {
                        myDynamicStateAdapter.setNewInstance(response.data);
                    } else {
                        myDynamicStateAdapter.addData(response.data);
                    }
                    if (myDynamicStateAdapter.getData().size() >= response.count) {
                        myDynamicStateAdapter.getLoadMoreModule().setEnableLoadMore(false);
                    }
                } else {
                    rvMyStatusList.setVisibility(View.GONE);
                    ll_dynamic_null.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void setView(PersonEntity.DataBean data) {
        Glide.with(this)
                .load(data.headImgUrl)
                .dontAnimate()
                .error(R.mipmap.ico_person_head)
                // “14”：设置模糊度(在0.0到25.0之间)，默认”25";"3":图片缩放比例,默认“1”。
                .apply(bitmapTransform(new BlurTransformation(14, 3)))
                .into(iv_bg);

        if (!TextUtils.isEmpty(data.headImgUrl))
            GlideUtils.loadImage(this, data.headImgUrl, rci_user_header);
        if (!TextUtils.isEmpty(data.answerMedal))
            GlideUtils.loadImage(this, data.answerMedal, iv_medal_name);
        tv_user_name.setText(data.nickname);
        String tenantName = "TA在 %s 团队";
        tv_tenant_name.setText(String.format(tenantName, data.tenantName));
        if (!TextUtils.isEmpty(data.introduction)) {
            tv_describe.setText(data.introduction);
        } else {
            if (UserAPI.getUserId().equals(userId)) {
                tv_describe.setEnabled(true);
                tv_describe.setText("你还没有填写个人简介，点击添加…");
            } else {
                tv_describe.setText("他还没有填写个人简介");
                tv_describe.setEnabled(false);
            }
        }

        if (data.medalList != null && data.medalList.size() > 0) {
            ll_medal_null.setVisibility(View.GONE);
            rv_badge_list.setVisibility(View.VISIBLE);
            GridLayoutManager glm = new GridLayoutManager(this, 4);
            myHomeMedalAdapter = new MyHomeMedalAdapter(this);
            rv_badge_list.setLayoutManager(glm);
            rv_badge_list.setAdapter(myHomeMedalAdapter);
            List<String> medalListFour = new ArrayList<>();
            int size = 0;
            if (data.medalList.size() >= 4) {
                size = 4;
            } else {
                size = data.medalList.size();
            }
            for (int i = 0; i < size; i++) {
                medalListFour.add(data.medalList.get(i));
            }
            myHomeMedalAdapter.setList(medalListFour);
        } else {
            ll_medal_null.setVisibility(View.VISIBLE);
            rv_badge_list.setVisibility(View.GONE);
        }

        if (dataBean.isConcerned) {
            ll_focus.setBackground(CommonUtil.getDrawable(R.drawable.bg_ffd7d7d7_stroke_360dp));
            tv_add_focus.setText("取消关注");
            iv_add_focus.setVisibility(View.GONE);
            tv_add_focus.setTextColor(CommonUtil.getColor(R.color.color_FF666666));
        } else {
            ll_focus.setBackground(CommonUtil.getDrawable(R.drawable.bg_ee4238_df2526_360dp));
            tv_add_focus.setText("关注");
            iv_add_focus.setVisibility(View.VISIBLE);
            tv_add_focus.setTextColor(CommonUtil.getColor(R.color.white));
        }
        if (dataBean.isLike) {
            tv_add_like.setText("已赞");
            ll_like.setBackground(CommonUtil.getDrawable(R.drawable.bg_fff63e5a_storke_360));
            iv_add_like.setImageResource(R.mipmap.ico_praised);
            tv_add_like.setTextColor(CommonUtil.getColor(R.color.color_FFF63E5A));
        } else {
            tv_add_like.setText("点赞");
            ll_like.setBackground(CommonUtil.getDrawable(R.drawable.bg_ee4238_df2526_360dp));
            iv_add_like.setImageResource(R.mipmap.ico_priase_white);
            tv_add_like.setTextColor(CommonUtil.getColor(R.color.white));
        }

        tv_sports_num.setText(data.sportCounts + "");
        tv_distance_km.setText(data.sportMileage + "");
        tv_like_num.setText(data.tinderCount + "");

        String medal = "荣誉徽章（ %s枚 ）";
        tv_medal_count.setText(String.format(medal, data.medalList.size()));

        tv_level.setText(data.titleName + "");
        tv_score.setText(data.answerFraction + "");
        String pass = "第%s关";
        tv_pass.setText(String.format(pass, data.levelNumber));

        indicator_seek_bar_we_long.setEnabled(false);
        if (data.myOngoingLongMarchProgressInfoDto != null) {
            tv_tiaozhan.setVisibility(View.VISIBLE);
            String startEndName = "%s - %s";
            tv_start_end_name.setText(String.format(startEndName,
                    data.myOngoingLongMarchProgressInfoDto.startPoint, data.myOngoingLongMarchProgressInfoDto.endPoint));
            indicator_seek_bar_we_long.setProgress((int) (data.myOngoingLongMarchProgressInfoDto.completionRate * 100));
            indicator_seek_bar_we_long.setDoubleProgress(data.myOngoingLongMarchProgressInfoDto.completionRate * 100);
            String finishRoad = "已挑战路段 %s/%s";
            tv_finish_load.setText(String.format(finishRoad, data.myOngoingLongMarchProgressInfoDto.completeNumber,
                    data.myOngoingLongMarchProgressInfoDto.totalNumber));
        } else {
            tv_start_end_name.setText("还未开启挑战~");
            tv_tiaozhan.setVisibility(View.GONE);
        }

        setBanner();
    }

    private void setBanner() {
        if (dataBean.myOngoingActivityLists != null && dataBean.myOngoingActivityLists.size() > 0) {
            banner.setVisibility(View.VISIBLE);
            ll_activity_null.setVisibility(View.GONE);
        } else {
            banner.setVisibility(View.GONE);
            ll_activity_null.setVisibility(View.VISIBLE);
            return;
        }
        List<MyOngoingActivityListsBean> bannerEntities = new ArrayList<>();
        for (int i = 0; i < dataBean.myOngoingActivityLists.size(); i++) {
            bannerEntities.add(dataBean.myOngoingActivityLists.get(i));
        }

        banner.addBannerLifecycleObserver(this)//添加生命周期观察者
                .setAdapter(new MyHomeBannerAdapter(this, bannerEntities))
                .setLoopTime(3000)
                .setIndicator(new RectangleIndicator(this));
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return false;
    }

    @OnClick({R.id.btn_finish, R.id.ll_focus, R.id.ll_like, R.id.tv_describe, R.id.rci_user_header, R.id.tv_medal_count, R.id.btn_finish_1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_finish:
            case R.id.btn_finish_1:
                finish();
                break;
            case R.id.tv_describe:
                Intent intent = new Intent(this, EditUserInfoActivity.class);
                intent.putExtra("TITlE_NAME", "个性签名");
                intent.putExtra("input_info", "请输入个性签名");
                startActivityForResult(intent, 99);
                break;
            case R.id.rci_user_header:
                if (dataBean != null && !TextUtils.isEmpty(dataBean.headImgUrl)) {
                    ArrayList<String> list = new ArrayList<>();
                    list.add(dataBean.headImgUrl);
                    Intent intent1 = new Intent(this, PhotoActivity.class);
                    intent1.putExtra("position", 0);
                    intent1.putStringArrayListExtra("list", list);
                    startActivity(intent1);
                }
                break;
            case R.id.ll_like:
                if (dataBean != null) {
                    if (dataBean.isLike) {
                        dataBean.isLike = false;
                    } else {
                        ll_like.setBackground(CommonUtil.getDrawable(R.drawable.bg_ee4238_df2526_360dp));
                        dataBean.isLike = true;
                    }
                    onLike(dataBean.isLike);
                }
                break;
            case R.id.ll_focus:
                if (null != dataBean) {
                    if (dataBean.isConcerned) {
                        dataBean.isConcerned = false;
                        onCancelFocus();
                    } else {
                        dataBean.isConcerned = true;
                        addFocus();
                    }
                }
                break;
            case R.id.tv_medal_count:
                Intent intent1 = new Intent(MyHomeActivityV2.this, MyMedalListActivity.class);
                intent1.putExtra(ActivityCompat.USER_ID, userId);
                intent1.putExtra(ActivityCompat.USER_NAME, dataBean.nickname);
                startActivity(intent1);
                break;
        }
    }

    private void onLike(boolean isLike) {
        JSONObject object = new JSONObject();
        try {
            object.put("likeDataId", userId);
            object.put("toLikeUserId", userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ActivityAPI().userAddOrCancelLike(isLike, object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                ToastUtils.showShort(response.getMessage());
                initData();
            }
        });
    }

    /**
     * 取消关注
     *
     * @param
     */
    private void onCancelFocus() {
        JSONObject object = new JSONObject();
        try {
            object.put("unConcernedUserId", userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new UserAPI().cancelFocus(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {

            }

            @Override
            public void onComplete() {
                super.onComplete();
                ToastUtils.showShort("取消关注成功");
                initData();
            }
        });
    }

    /**
     * 关注
     *
     * @param
     */
    private void addFocus() {
        JSONObject object = new JSONObject();
        try {
            object.put("concernedUserId", userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new UserAPI().addFocus(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {

            }

            @Override
            public void onComplete() {
                super.onComplete();
                ToastUtils.showShort("关注成功");
                initData();
            }
        });
    }
}
